﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Identity.API.Filter
{
    /// <summary>
    /// 自定义异常处理
    /// </summary>
    public class CustomExceptionFilterAttribute : IExceptionFilter
    {
        private ILogger<CustomExceptionFilterAttribute> _logger = null;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger"></param>
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
        {
            this._logger = logger;
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                object result = new { Code=400, Message= context.Exception.Message };
                context.Result = new JsonResult(result);
                context.HttpContext.Response.StatusCode = 400;
                this._logger.LogError(context.Exception.StackTrace);
            }
            context.ExceptionHandled = true;
        }
    }
}
